import {
  MigrationInterface,
  QueryRunner,
  Table,
  TableForeignKey,
  TableIndex,
} from 'typeorm';

export class CreateMessagesAndNotificationsTables1730625000000
  implements MigrationInterface
{
  public async up(queryRunner: QueryRunner): Promise<void> {
    // 创建会话表
    await queryRunner.createTable(
      new Table({
        name: 'conversations',
        columns: [
          {
            name: 'id',
            type: 'int',
            isPrimary: true,
            isGenerated: true,
            generationStrategy: 'increment',
          },
          {
            name: 'conversationId',
            type: 'varchar',
            length: '50',
            isUnique: true,
            comment: '会话ID（由较小的userId和较大的userId组合生成）',
          },
          {
            name: 'user1Id',
            type: 'int',
            comment: '用户1的ID（较小的ID）',
          },
          {
            name: 'user2Id',
            type: 'int',
            comment: '用户2的ID（较大的ID）',
          },
          {
            name: 'lastMessageContent',
            type: 'text',
            isNullable: true,
            comment: '最后一条消息内容',
          },
          {
            name: 'lastMessageAt',
            type: 'timestamp',
            isNullable: true,
            comment: '最后一条消息时间',
          },
          {
            name: 'user1UnreadCount',
            type: 'int',
            default: 0,
            comment: '用户1的未读消息数',
          },
          {
            name: 'user2UnreadCount',
            type: 'int',
            default: 0,
            comment: '用户2的未读消息数',
          },
          {
            name: 'createdAt',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
            comment: '创建时间',
          },
          {
            name: 'updatedAt',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
            onUpdate: 'CURRENT_TIMESTAMP',
            comment: '更新时间',
          },
        ],
      }),
      true,
    );

    // 创建会话表索引
    await queryRunner.createIndex(
      'conversations',
      new TableIndex({
        name: 'IDX_conversations_user1Id_user2Id',
        columnNames: ['user1Id', 'user2Id'],
        isUnique: true,
      }),
    );
    await queryRunner.query(
      'CREATE INDEX `IDX_conversations_user1Id` ON `conversations` (`user1Id`)',
    );
    await queryRunner.query(
      'CREATE INDEX `IDX_conversations_user2Id` ON `conversations` (`user2Id`)',
    );

    // 创建消息表
    await queryRunner.createTable(
      new Table({
        name: 'messages',
        columns: [
          {
            name: 'id',
            type: 'int',
            isPrimary: true,
            isGenerated: true,
            generationStrategy: 'increment',
          },
          {
            name: 'conversationId',
            type: 'varchar',
            length: '50',
            comment: '会话ID',
          },
          {
            name: 'senderId',
            type: 'int',
            comment: '发送者ID',
          },
          {
            name: 'receiverId',
            type: 'int',
            comment: '接收者ID',
          },
          {
            name: 'type',
            type: 'enum',
            enum: ['text', 'image', 'video', 'audio', 'file'],
            default: "'text'",
            comment: '消息类型',
          },
          {
            name: 'content',
            type: 'text',
            comment: '消息内容',
          },
          {
            name: 'mediaUrl',
            type: 'text',
            isNullable: true,
            comment: '媒体文件URL',
          },
          {
            name: 'isRead',
            type: 'boolean',
            default: false,
            comment: '是否已读',
          },
          {
            name: 'readAt',
            type: 'timestamp',
            isNullable: true,
            comment: '已读时间',
          },
          {
            name: 'isDeletedBySender',
            type: 'boolean',
            default: false,
            comment: '是否已删除（发送者）',
          },
          {
            name: 'isDeletedByReceiver',
            type: 'boolean',
            default: false,
            comment: '是否已删除（接收者）',
          },
          {
            name: 'createdAt',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
            comment: '创建时间',
          },
          {
            name: 'updatedAt',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
            onUpdate: 'CURRENT_TIMESTAMP',
            comment: '更新时间',
          },
        ],
      }),
      true,
    );

    // 创建消息表外键
    await queryRunner.createForeignKey(
      'messages',
      new TableForeignKey({
        columnNames: ['senderId'],
        referencedColumnNames: ['id'],
        referencedTableName: 'users',
        onDelete: 'CASCADE',
      }),
    );

    await queryRunner.createForeignKey(
      'messages',
      new TableForeignKey({
        columnNames: ['receiverId'],
        referencedColumnNames: ['id'],
        referencedTableName: 'users',
        onDelete: 'CASCADE',
      }),
    );

    // 创建消息表索引
    await queryRunner.createIndex(
      'messages',
      new TableIndex({
        name: 'IDX_messages_senderId_receiverId',
        columnNames: ['senderId', 'receiverId'],
      }),
    );
    await queryRunner.createIndex(
      'messages',
      new TableIndex({
        name: 'IDX_messages_conversationId_createdAt',
        columnNames: ['conversationId', 'createdAt'],
      }),
    );
    await queryRunner.query(
      'CREATE INDEX `IDX_messages_conversationId` ON `messages` (`conversationId`)',
    );

    // 创建通知表
    await queryRunner.createTable(
      new Table({
        name: 'notifications',
        columns: [
          {
            name: 'id',
            type: 'int',
            isPrimary: true,
            isGenerated: true,
            generationStrategy: 'increment',
          },
          {
            name: 'userId',
            type: 'int',
            comment: '接收者ID',
          },
          {
            name: 'triggerId',
            type: 'int',
            isNullable: true,
            comment: '触发者ID',
          },
          {
            name: 'type',
            type: 'enum',
            enum: [
              'friend_request',
              'friend_accepted',
              'work_liked',
              'work_collected',
              'work_commented',
              'comment_replied',
              'system',
            ],
            comment: '通知类型',
          },
          {
            name: 'title',
            type: 'varchar',
            length: '200',
            comment: '通知标题',
          },
          {
            name: 'content',
            type: 'text',
            comment: '通知内容',
          },
          {
            name: 'data',
            type: 'json',
            isNullable: true,
            comment: '关联数据（JSON格式）',
          },
          {
            name: 'isRead',
            type: 'boolean',
            default: false,
            comment: '是否已读',
          },
          {
            name: 'readAt',
            type: 'timestamp',
            isNullable: true,
            comment: '已读时间',
          },
          {
            name: 'isDeleted',
            type: 'boolean',
            default: false,
            comment: '是否已删除',
          },
          {
            name: 'createdAt',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
            comment: '创建时间',
          },
        ],
      }),
      true,
    );

    // 创建通知表外键
    await queryRunner.createForeignKey(
      'notifications',
      new TableForeignKey({
        columnNames: ['userId'],
        referencedColumnNames: ['id'],
        referencedTableName: 'users',
        onDelete: 'CASCADE',
      }),
    );

    await queryRunner.createForeignKey(
      'notifications',
      new TableForeignKey({
        columnNames: ['triggerId'],
        referencedColumnNames: ['id'],
        referencedTableName: 'users',
        onDelete: 'SET NULL',
      }),
    );

    // 创建通知表索引
    await queryRunner.createIndex(
      'notifications',
      new TableIndex({
        name: 'IDX_notifications_userId_isRead',
        columnNames: ['userId', 'isRead'],
      }),
    );
    await queryRunner.createIndex(
      'notifications',
      new TableIndex({
        name: 'IDX_notifications_userId_createdAt',
        columnNames: ['userId', 'createdAt'],
      }),
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // 删除通知表
    await queryRunner.dropTable('notifications');

    // 删除消息表
    await queryRunner.dropTable('messages');

    // 删除会话表
    await queryRunner.dropTable('conversations');
  }
}
